import { VxeGridPropTypes } from '@/components/VxeTable';
import { hasPermission } from '@/utils/permission';
import { Switch, message } from 'ant-design-vue';
import { EleTag } from 'ele-admin-pro';
import { h } from 'vue';
import { updateUserStatus } from '@/api/system/user';

const VxeColumn: VxeGridPropTypes.Columns = [
  {
    type: 'checkbox',
    width: 40
  },
  {
    title: '用户名',
    field: 'userName',
    width: 110
  },
  {
    title: '昵称',
    field: 'nickName',
    width: 110
  },
  {
    title: '头像',
    field: 'avatar',
    width: 110
    // slots: { customRender: 'avatar' },
  },
  {
    title: '出生日期',
    field: 'birthday',
    width: 110
  },
  {
    title: '性别',
    field: 'sex',
    width: 60,
    slots: {
      default: ({ row }) => {
        const sex = row.sex;
        switch (sex) {
          case 1:
            return h(EleTag, { color: 'blue' }, () => '男');
          case 2:
            return h(EleTag, { color: 'red' }, () => '女');
          default:
            return h(EleTag, { color: 'orange' }, () => '未知');
        }
      }
    }
  },
  {
    title: '邮箱',
    field: 'email',
    width: 100
  },
  {
    title: '手机号码',
    field: 'phone',
    width: 100
  },
  {
    title: '真实姓名',
    field: 'realName',
    width: 100
  },
  {
    title: '证件号码',
    field: 'idCard',
    width: 100
  },
  {
    title: '状态',
    field: 'status',
    width: 100,
    slots: {
      default: ({ row }) => {
        const record = row;
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.status === 1,
          checkedChildren: '已启用',
          unCheckedChildren: '已禁用',
          disabled: !hasPermission('sysUser:setStatus'),
          loading: record.pendingStatus,
          onChange(checked: boolean) {
            record.pendingStatus = true;
            const newStatus = checked ? 1 : 2;
            updateUserStatus(record.id, newStatus)
              .then(() => {
                record.status = newStatus;
                message.success(`已成功修改账号状态`);
              })
              .catch(() => {
                message.error('修改账号状态失败');
              })
              .finally(() => {
                record.pendingStatus = false;
              });
          }
        });
      }
    }
  },
  {
    title: '备注',
    field: 'remark',
    width: 90
  },
  {
    title: '创建时间',
    field: 'createTime',
    visible: false
  },
  {
    width: 140,
    title: '操作',
    align: 'center',
    slots: { default: 'action' },
    fixed: 'right'
  }
];

export default VxeColumn;
